package com.android.xunxian.activity;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.xunxian.MyApplication;
import com.android.xunxian.R;
import com.android.xunxian.adapter.XunxAdapter;
import com.android.xunxian.entry.JLTable;
import com.android.xunxian.entry.JWdu;
import com.android.xunxian.entry.Xunx;
import com.android.xunxian.utils.UConstants;
import com.android.xunxian.utils.Util;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.ex.DbException;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;

/**
 * Created by zouqh on 2016/7/16.
 */
public class UpdateXunxActivity extends Activity implements View.OnClickListener {


    @InjectView(R.id.close)
    ImageView close;
    @InjectView(R.id.title_text)
    TextView titleText;
    @InjectView(R.id.ritgh_icon)
    ImageView ritghIcon;
    @InjectView(R.id.ritgh_text)
    TextView ritghText;
    @InjectView(R.id.upBtn)
    TextView upBtn;

    ListView listview;
    ProgressDialog dialog;
    private List<Xunx> xunxList;
    private XunxAdapter adapter;//
    private String imgPath;
    private String fileName;
    private List<JWdu> jWduList;//经纬度文件生成
    private List<JLTable> jlTableList;//记录文件生成
    private String fileName1;

    private List<File> fileList;
    private Dialog Jdialog;
    String str1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.xunx_activity);
        listview=(ListView)findViewById(R.id.listview);
        ButterKnife.inject(this);
        titleText.setText("巡线上传");
        ritghText.setText("上传");
        close.setOnClickListener(this);
        ritghText.setOnClickListener(this);
        upBtn.setOnClickListener(this);
        xunxList=new ArrayList<>();
        fileList=new ArrayList<>();
        try {

            xunxList =  MyApplication.dbManager.selector(Xunx.class).where("SPLANZT", "=", "执行中").findAll();
            if (xunxList != null&&xunxList.size()>0) {
                jWduList=MyApplication.dbManager.selector(JWdu.class).findAll();
                ritghText.setVisibility(View.VISIBLE);
               Log.i("ssssssssssss","");
                imgPath = Environment.getExternalStorageDirectory().getPath()
                        + File.separator + "Xunxian" + File.separator + xunxList.get(0).getID() + File.separator;
                fileName= xunxList.get(0).getID()+"_xxRote.txt";
//                fileName1= xunxList.get(0).getID()+"_xxJlb.txt";
                upBtn.setVisibility(View.VISIBLE);
            }else{
               Toast.makeText(getApplicationContext(),"您还没有执行的路线",Toast.LENGTH_SHORT).show();

            }

        } catch (DbException e) {
            e.printStackTrace();
        }
        adapter=new XunxAdapter(this,xunxList);
        listview.setAdapter(adapter);


    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){

            case R.id.close:
                finish();
                break;

            case R.id.upBtn:
                pointDialog("任务结束就不能修改,是否继续？");
                break;
            case R.id.ritgh_text:
                    if(jWduList!=null&&jWduList.size()>0){
                    Gson gson = new Gson();
                    String json=gson.toJson(jWduList);//将更新数组
                    String str="{\"success\":\"true\", \"total\":\""+jWduList.size()+"\",\"rows\":"+json+"}";
                    new Util(this).writeTxtToFile(str,imgPath,fileName);
                        JLTable jlTable = new JLTable();
                        jlTable.setLatitude("");
                        jlTable.setLongitude("");
                        jlTable.setPlanId(xunxList.get(0).getXunId());
                        jlTable.setFileKind("路线");
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
                                "yyyyMMddHHmmss");
                        simpleDateFormat.format(new Date());
                        jlTable.setFileDt( simpleDateFormat.format(new Date()));
                        jlTable.setFileName(fileName);
                        jlTable.setFileMemo("");
                        try {
                            MyApplication.dbManager.saveOrUpdate(jlTable);
                            jlTableList=MyApplication.dbManager.selector(JLTable.class).findAll();
                            String json1=gson.toJson(jlTableList);//将更新数组
                            Log.i("aaaaaaaaaaaaaaa",json);
                            Log.i("BBBBBBBBBBBBBB",json1);
                             str1="{\"success\":\"true\", \"total\":\""+jlTableList.size()+"\",\"rows\":"+json1+"}";
//                            new Util(this).writeTxtToFile(str1,imgPath,fileName1);
                            upDate();

                        } catch (DbException e) {
                            e.printStackTrace();
                        }
                    }
                break;
        }
    }



    /**
     * 提示
     */
    private void pointDialog(String str) {
        LayoutInflater inflaterDl = LayoutInflater.from(this);
        View layout = inflaterDl.inflate(R.layout.prompt_dialog,
                null);
        // 对话框
        Jdialog = new Dialog(this);
        Jdialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        Jdialog.show();

        Jdialog.setContentView(layout);
        TextView sure = (TextView) layout.findViewById(R.id.sureExti);
        TextView cancle = (TextView) layout.findViewById(R.id.cancleExti);
        TextView dialogTitle = (TextView) layout.findViewById(R.id.dialogTitle);

        dialogTitle.setText(str);
        sure.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
//
                xunxList.get(0).setSPLANZT("已完成");
                try {
                    MyApplication.dbManager.saveOrUpdate( xunxList.get(0));
                    xunxList.clear();
                    adapter.notifyDataSetChanged();

                } catch (DbException e) {
                    e.printStackTrace();
                }
                Jdialog.cancel();


            }
        });
        cancle.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                Jdialog.cancel();
            }
        });

    }

    File[] files=null;
    //获取巡线列表
    private void upDate() {
        dialog = ProgressDialog.show(this, null, "上传中...", true, false);
        File file=new File(imgPath);

        if (file.isDirectory()){
           files = file.listFiles();
            if (null==files){
                dialog.dismiss();
                Toast.makeText(getApplicationContext(),"没有文件上传",10).show();
                return;
            }
        }
        RequestParams params = new RequestParams(UConstants.XX_UPDATE);
//        params.setMultipart(true);
        params.addBodyParameter("LKind","CBJ");
        params.addBodyParameter("EmpId",UConstants.EmpId);
        params.addBodyParameter("PartId", UConstants.PartId );
        params.addBodyParameter("FileInfo",str1);

        for (int i=0;i<files.length;i++){
            System.out.println(files[i].getPath());
            params.addBodyParameter("FILES", files[i]);
        }

        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Util.printLog("getMerchants------------onSuccess-----", result);
                if (result.length() > 0) {
                    try {
                        JSONObject object = new JSONObject(result);
//                        allPage = Integer.parseInt(object.getString("total"));
//                        allPage = (int) Math.ceil((double) allPage / pageSize);
                        boolean success = object.getBoolean("success");
//                        String msg = object.getString("msg");
                        if (success) {
                            Toast.makeText(x.app(), "上传成功！", Toast.LENGTH_SHORT).show();
                            for (int i =0;i<files.length;i++){
                                files[i].delete();
                            }
                            try {
                                MyApplication.dbManager.delete(JWdu.class);
                                MyApplication.dbManager.delete(JLTable.class);
                            } catch (DbException e) {
                                e.printStackTrace();
                            }

                        } else {
                            Toast.makeText(x.app(), "上传失败！", Toast.LENGTH_SHORT).show();
                        }
//                        Toast.makeText(x.app(), msg, Toast.LENGTH_LONG).show();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                dialog.dismiss();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Util.printLog("getMerchants------------onError-----", ex.getMessage() + "");

                Toast.makeText(x.app(), "连接失败！", Toast.LENGTH_LONG).show();
                dialog.dismiss();
            }

            @Override
            public void onCancelled(CancelledException cex) {

                Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
                Util.printLog("getMerchants------------onCancelled-----", cex.getMessage() + "");
                dialog.dismiss();
            }

            @Override
            public void onFinished() {

            }
        });
    }




}